package com.demo.maintenance.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.demo.maintenance.R;
import com.demo.maintenance.adapter.BaseUploadAdapter;
import com.demo.maintenance.bean.BaseResponse;
import com.demo.maintenance.bean.ChildInfoResponse;
import com.demo.maintenance.bean.StatusResponse;
import com.demo.maintenance.bean.UploadResponse;
import com.demo.maintenance.contant.Global;
import com.demo.maintenance.utils.ActivityManager;
import com.demo.maintenance.utils.AntiShakeUtils;
import com.demo.maintenance.utils.DensityUtils;
import com.demo.maintenance.utils.HttpManager;
import com.demo.maintenance.utils.SystemBarTintManager;
import com.demo.maintenance.widget.GlideImageLoader;
import com.demo.maintenance.widget.PopSpinnerView;
import com.demo.maintenance.widget.ninegridview.ImagePickerLoader;
import com.demo.maintenance.widget.ninegridview.NineGirdImageContainer;
import com.demo.maintenance.widget.ninegridview.NineGridBean;
import com.demo.maintenance.widget.ninegridview.NineGridView;
import com.hjq.toast.ToastUtils;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.lwkandroid.imagepicker.ImagePicker;
import com.lwkandroid.imagepicker.data.ImageBean;
import com.lwkandroid.imagepicker.data.ImagePickType;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class UploadActivity extends AppCompatActivity {

    private NineGridView ninegridview;

    private TextView uploadBtn;

    private int requestCode = 201;

    public List<NineGridBean> resultList = new ArrayList<>();

    private PopSpinnerView sp_status_type;

    private PopSpinnerView sp_child;

    private List<ChildInfoResponse.Data> childInfoList = new ArrayList<>();

    private List<StatusResponse.Data> statusTypeList = new ArrayList<>();

    private EditText et_desc;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        QMUIStatusBarHelper.translucent(this);
        SystemBarTintManager.setStatusBarDarkTheme(this, true);
        setContentView(R.layout.activity_upload);

        findViewById(R.id.common_back_iv).setOnClickListener(v -> finish());
        ((TextView) findViewById(R.id.common_content_tv)).setText("UPLOAD");

        uploadBtn = findViewById(R.id.account_register_start);
        uploadBtn.setOnClickListener(v -> {
            if (AntiShakeUtils.isInvalidClick(v)){
                return;
            }
            uploadChildStatus();
        });

        et_desc = findViewById(R.id.et_desc);

        // 九宫格
        ninegridview = findViewById(R.id.ninegridview);
        ninegridview.setImageLoader(new GlideImageLoader());
        ninegridview.setColumnCount(1);
        ninegridview.setIsEditMode(true);
        ninegridview.setSingleImageSize(200);
        ninegridview.setSingleImageRatio(0.8f);
        ninegridview.setMaxNum(1);
        ninegridview.setSpcaeSize(4);
        ninegridview.setRatioOfDeleteIcon(0.3f);
        ninegridview.setIcAddMoreResId(R.mipmap.ic_ngv_add_pic);
        ninegridview.setDataList(resultList);
        ninegridview.setOnItemClickListener(new NineGridView.onItemClickListener() {
            @Override
            public void onNineGirdAddMoreClick(int cha) {
                new ImagePicker()
                        .cachePath(Environment.getExternalStorageDirectory().getAbsolutePath())
                        .pickType(ImagePickType.SINGLE)
                        .displayer(new ImagePickerLoader())
                        .maxNum(cha)
                        .start(ActivityManager.getTopActivity(), requestCode);
            }

            @Override
            public void onNineGirdItemClick(int position, NineGridBean gridBean, NineGirdImageContainer imageContainer) {

            }

            @Override
            public void onNineGirdItemDeleted(int position, NineGridBean gridBean, NineGirdImageContainer imageContainer) {
                try {
                    resultList.remove(gridBean);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        sp_status_type = findViewById(R.id.sp_status_type);
        sp_child = findViewById(R.id.sp_child);

        getChildList();
        getStatusTypeList();
    }

    /**
     * upload child status
     */
    private void uploadChildStatus() {

        // check params
        if (sp_child.getSelectIndex() <= 0){
            ToastUtils.show("please select child");
            return;
        }

        if (sp_status_type.getSelectIndex() <= 0){
            ToastUtils.show("please select status");
            return;
        }

        if (TextUtils.isEmpty(et_desc.getText().toString())){
            ToastUtils.show("please input status description");
            return;
        }

        WaitDialog.show("Uploading");

        String url = Global.ipAddress + "/app/insertChildStatus";

        Map<String, String> params = new HashMap<>();
        params.put("childId", String.valueOf(childInfoList.get(sp_child.getSelectIndex()).childId));
        params.put("statusType", statusTypeList.get(sp_status_type.getSelectIndex()).status);
        params.put("statusDesc", et_desc.getText().toString());
        if (resultList != null && !resultList.isEmpty()) {
            params.put("statusPic", resultList.get(0).onlineImageUrl);
        }

        try{
            HttpManager.postJson(url, params, new HttpManager.NetworkCallBack() {
                @Override
                public void onSuccess(String successInfo) {
                    try{
                        Log.e("monitoring", successInfo);

                        BaseResponse response = JSON.parseObject(successInfo, BaseResponse.class);
                        if (response.code == 200){
                            runOnUiThread(() -> {
                                ToastUtils.show("Upload Success");
                                finish();
                            });
                        }else {
                            Log.e("monitoring", "get child list failed !");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(String errorInfo) {
                    Log.e("monitoring", errorInfo);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * get Child list
     */
    private void getChildList(){
        String url = Global.ipAddress + "/app/getChildList?teacherPhone=" + Global.userResponse.data.userPhone;
        HttpManager.get(url, new HttpManager.NetworkCallBack() {
            @Override
            public void onSuccess(String successInfo) {
                try{
                    Log.e("monitoring", successInfo);

                    ChildInfoResponse childInfoResponse = JSON.parseObject(successInfo, ChildInfoResponse.class);
                    if (childInfoResponse.code == 200 && childInfoResponse.data != null){
                        childInfoList = childInfoResponse.data;
                        runOnUiThread(() -> {
                            sp_child.init(childInfoList.size(), DensityUtils.dip2px(180),
                                    position -> childInfoList.get(position).childName);
                        });
                    }else {
                        Log.e("monitoring", "get child list failed !");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorInfo) {
                Log.e("monitoring", errorInfo);
            }
        });
    }

    private void getStatusTypeList(){
        String url = Global.ipAddress + "/app/getStatusList";
        HttpManager.get(url, new HttpManager.NetworkCallBack() {
            @Override
            public void onSuccess(String successInfo) {
                try{
                    Log.e("monitoring", successInfo);

                    StatusResponse statusResponse = JSON.parseObject(successInfo, StatusResponse.class);
                    if (statusResponse.code == 200 && statusResponse.data != null){
                        statusTypeList = statusResponse.data;
                        runOnUiThread(() -> {
                            sp_status_type.init(statusTypeList.size(), DensityUtils.dip2px(180),
                                    position -> statusTypeList.get(position).dictLabel);
                        });
                    }else {
                        Log.e("monitoring", "get status type list failed !");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorInfo) {
                Log.e("monitoring", errorInfo);
            }
        });
    }

    public void uploadFile(String filePath, BaseUploadAdapter.UploadSuccessListener listener){
        WaitDialog.show("Uploading");

        String url = Global.ipAddress + "/app/upload";

        try {
            HttpManager.postFile(url, filePath, new HttpManager.NetworkCallBack() {
                @Override
                public void onSuccess(String successInfo) {
                    try{
                        UploadResponse uploadResponse = JSON.parseObject(successInfo, UploadResponse.class);
                        if (uploadResponse.code == 200){
                            Log.e("monitoring", uploadResponse.url);

                            NineGridBean nineGridBean = new NineGridBean(filePath);
                            nineGridBean.onlineImageUrl = uploadResponse.url;
                            resultList.add(nineGridBean);

                            runOnUiThread(() -> ninegridview.setDataList(resultList));

                        }else {
                            ToastUtils.show("Upload Failed");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        ToastUtils.show("Upload Failed");
                    }
//
                }

                @Override
                public void onError(String errorInfo) {
                    Log.e("monitoring", TextUtils.isEmpty(errorInfo) ? "nothing" : errorInfo);
                    ToastUtils.show("Upload Failed");
                }

                @Override
                public void onFinal() {
                    WaitDialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            WaitDialog.dismiss();
            ToastUtils.show("Upload Failed");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == this.requestCode && resultCode == RESULT_OK && data != null) {
            List<ImageBean> list = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA);
            if (list == null || list.isEmpty()) {
                return;
            }
            ImageBean imageBean = list.get(0);
            if (imageBean == null || TextUtils.isEmpty(imageBean.getImagePath())) {
                return;
            }
            Log.e("monitoring", "current activity" + ActivityManager.getTopActivity().getClass().getSimpleName());

            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    uploadFile(imageBean.getImagePath(), fileUrl -> {
                        ActivityManager.getTopActivity().runOnUiThread(() -> {
                            NineGridBean nineGridBean = new NineGridBean(imageBean.getImagePath());
                            nineGridBean.onlineImageUrl = fileUrl;
                            resultList.add(nineGridBean);
                        });
                    });
                    timer.cancel();
                }
            }, 300);
        }
    }
}
